﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Core.Common;
using TTSClient.Models;

namespace TTSClient
{
    public partial class TTSClientForm : Form
    {
        private static AppSetting AppSetting => AppSetting.Current;
        private static ICollection<TTSModel> TTSModels => TTSModel.TTSModels;
        private static ICollection<Language> Languages;
        private static int TransferIndex = 1;
        public TTSClientForm()
        {
            InitializeComponent();
            FormClosing += Form_Close;
        }

        private void TTSClientForm_Load(object sender, EventArgs e)
        {
            if (AppSetting == null)
            {
                MessageBox.Show("配置文件错误, 系统无法正常打开使用, 清检查配置文件后在重新打开!");
                Application.Exit();
            }

            if (!Directory.Exists(AppSetting.RootPath))
            {
                Directory.CreateDirectory(AppSetting.RootPath);
            }

            lblMessage.Text = "正在初始化语言列表, 请稍后!";

            new Task(async () =>
            {
                try
                {
                    Languages = await TTSUtil.GetLanguages();
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"初始化语言列表失败, 详情 {ex.Message}!");
                }

                if (Languages.IsNotNullOrEmpty())
                {
                    try
                    {
                        TTSModel.Read(Languages);
                        TransferIndex = TTSModels.Count + 1;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"读取已保存数据出现错误, 详情 {ex.Message}!");
                    }

                    cbLanguage.Invoke(new Action(() =>
                    {
                        cbLanguage.DataSource = Languages;
                        cbLanguage.SelectedValue = AppSetting.VcnCode;
                        txtText.Text = "您提交的身份信息已绑定其他用户, 如非您本人操作, 则您的身份信息可能已经泄漏, 请立即联系管理员核查处理!";
                        RefreshListView();

                        lblMessage.Text = "语言列表初始化完成, 现在可以开始使用了!";
                    }));
                }
                else
                {
                    if (MessageBox.Show($"语言列表初始化失败, 抱歉系统无法使用!", "错误", MessageBoxButtons.OK) == DialogResult.OK)
                    {
                        Application.Exit();
                    }
                }
            }).Start();
        }

        private void btnTransfer_Click(object sender, EventArgs e)
        {
            if (AppSetting.AppId.IsNullOrEmpty() || AppSetting.ApiKey.IsNullOrEmpty() || AppSetting.ApiSecret.IsNullOrEmpty())
            {
                MessageBox.Show("请先设置您的讯飞账户!");
                return;
            }

            var text = txtText.Text.Trim();
            if (text.IsNullOrEmpty())
            {
                MessageBox.Show("请输入转换文字!");
                return;
            }

            var fileNameText = txtFileName.Text.Trim();
            if (fileNameText.IsNullOrEmpty())
            {
                MessageBox.Show("请输入文件名!");
                return;
            }

            if (cbLanguage.SelectedValue == null && cbLanguage.Text.Trim().IsNullOrEmpty())
            {
                MessageBox.Show("请选择转换语言!");
                return;
            }

            fileNameText += ".mp3";
            var fileName = Path.Combine(AppSetting.RootPath, fileNameText);
            var canWriteFile = !File.Exists(fileName) || MessageBox.Show($"文件: {fileNameText} 已存在, 保存将覆盖已有文件!", "注意", MessageBoxButtons.OKCancel) == DialogResult.OK;
            if (canWriteFile)
            {
                var model = new TTSModel
                {
                    Index = TransferIndex++,
                    Path = fileNameText,
                    Text = text,
                    FullPath = fileName,
                    Started = true,
                };

                model.Code = cbLanguage.SelectedValue.ToString();
                model.VcnText = Languages.FirstOrDefault(x => x.Code == model.Code)?.Text;

                lock (TTSModels)
                {
                    if (TTSModels.Any(x => x.Path == model.Path))
                    {
                        MessageBox.Show($"文件 {fileNameText} 正在转换中请稍后!");
                        return;
                    }

                    TTSModels.Add(model);
                }

                Task.Run(async () => await StartTransferAsync(model));
                RefreshStatus();
                MessageBox.Show($"语音文件 {fileNameText} 正在转换中, 请稍候! 转换过程中, 您可以点击重置按钮继续输入新的内容继续进行转换!");
            }
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            txtText.Text = string.Empty;
            cbLanguage.SelectedIndex = 0;
            txtFileName.Text = string.Empty;
        }

        private void Form_Close(object sender, FormClosingEventArgs e)
        {
            try
            {
                if (TTSModels.Any(x => x.Started && !x.Ended) && MessageBox.Show("还有没有转换完成的语音文件, 是否一定要退出?", "注意", MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                {
                    e.Cancel = true;
                }
                else
                {
                    TTSModel.Write();
                    MessageBox.Show("已转换数据保存完成, 您可以安全退出!");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存出现错误, 详情 {ex.Message}!");
            }
        }

        private void topMenuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            switch (e.ClickedItem.Name)
            {
                case nameof(toolStripMenuItemOpenFolder):
                    Process.Start("explorer.exe", AppSetting.RootPath);
                    break;
                case nameof(toolStripMenuItemSetting):
                    var settingForm = new SettingForm();
                    settingForm.Languages = Languages;
                    var dialogResult = settingForm.ShowDialog();
                    if (dialogResult == DialogResult.OK)
                    {
                        cbLanguage.SelectedValue = AppSetting.VcnCode;
                    }
                    break;
                default:
                    break;
            }
        }

        private async Task StartTransferAsync(TTSModel model)
        {
            var text = Convert.ToBase64String(Encoding.UTF8.GetBytes(model.Text));
            await new TTSUtil().StartAsync(new RequestModel
            {
                Common = new RequestCommonModel { AppId = AppSetting.AppId },
                Business = new RequestBusinessModel { Vcn = model.Code },
                Data = new RequestDataModel { Text = text }
            }, model.FullPath, () =>
            {
                MessageBox.Show($"文件 {model.Path} 已转换完成!");
                lock (TTSModels)
                {
                    model.Success = true;
                    model.Ended = true;
                }

                listView.Invoke(new Action(RefreshListView));
                lblMessage.Invoke(new Action(RefreshStatus));
            }, ex =>
            {
                lock (TTSModels)
                {
                    model.Ended = true;
                }

                MessageBox.Show($"文件 {model.Path} 转换出错, " + ex.Message);
            });
        }

        private void RefreshStatus()
        {
            lock (TTSModels)
            {
                var message = string.Empty;
                if (TTSModels.IsNotNullOrEmpty() && TTSModels.Any(x => !x.Success))
                {
                    message = TTSModels.Where(x => !x.Success).Select(x => x.Path).ToString<string>();
                }

                lblMessage.Text = $"转换中的文件: {message ?? "无"}";
            }
        }

        private void RefreshListView()
        {
            List<TTSModel> list;
            lock (TTSModels)
            {
                list = TTSModels.ToList();
            }

            if (list.IsNotNullOrEmpty() && list.Any(x => x.Success))
            {
                //数据更新，UI暂时挂起，直到EndUpdate绘制控件，可以有效避免闪烁并大大提高加载速度 
                listView.BeginUpdate();
                foreach (var model in list.Where(x => x.Success))
                {
                    if (!listView.Items.ContainsKey(model.Path))
                    {
                        ListViewItem lvi = new ListViewItem
                        {
                            //通过与imageList绑定，显示imageList中第i项图标 
                            //ImageIndex = 0,
                            Text = model.Index.ToString(),
                            Name = model.Path
                        };

                        //lvi.SubItems.Add(model.Index.ToString());
                        //lvi.SubItems.Add(model.Code);
                        lvi.SubItems.Add(model.VcnText);
                        lvi.SubItems.Add(model.Path);
                        lvi.SubItems.Add(model.Text);
                        listView.Items.Add(lvi);
                    }
                }

                //结束数据处理，UI界面一次性绘制。 
                listView.EndUpdate();
            }
        }
    }
}
